package com.it.ems.service.impl;

import com.it.ems.entity.User;
import com.it.ems.mapper.UserMapper;
import com.it.ems.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    @Override
    @Transactional
    public boolean register(User user) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            return false;
        }
        // 检查手机号是否已存在
        if (user.getPhoneNumber() != null && userMapper.findByPhone(user.getPhoneNumber()) != null) {
            return false;
        }
        // 直接保存明文密码，不加密
        return userMapper.insert(user) > 0;
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        // 直接比对明文密码
        if (user != null && password.equals(user.getPassword())) {
            return user;
        }
        return null;
    }

    @Override
    @Transactional
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 使用 passwordEncoder 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("旧密码不正确");
        }

        // 加密新密码并更新
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        return userMapper.updatePassword(userId, encodedNewPassword) > 0;
    }

    @Override
    @Transactional
    public boolean updateUserInfo(User user) {
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public void updateProfile(User user) {
        // 根据 ID 获取现有用户，确保只更新允许修改的字段
        User existingUser = userMapper.findById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        existingUser.setUsername(user.getUsername());
        existingUser.setPhoneNumber(user.getPhoneNumber());
        existingUser.setRealName(user.getRealName());
        userMapper.updateProfile(existingUser);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    @Transactional
    public void save(User user) {
        if (user.getId() == null) {
            // 新用户，加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userMapper.insert(user);
        } else {
            // 更新用户
            User existingUser = userMapper.findById(user.getId());
            if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            } else {
                user.setPassword(existingUser.getPassword());
            }
            userMapper.update(user);
        }
    }

    @Override
    @Transactional
    public void updateUserRole(Long userId, String newRole) {
        System.out.println("正在更新用户角色 - 用户ID: " + userId + ", 新角色: " + newRole);
        
        // 检查用户是否存在
        User user = userMapper.findById(userId);
        if (user == null) {
            System.out.println("用户不存在 - 用户ID: " + userId);
            throw new RuntimeException("用户不存在");
        }
        
        // 检查新角色是否有效
        if (!newRole.equals("ROLE_ADMIN") && !newRole.equals("ROLE_USER")) {
            System.out.println("无效的角色: " + newRole);
            throw new RuntimeException("无效的角色");
        }
        
        try {
            // 更新用户角色
            userMapper.updateUserRole(userId, newRole);
            System.out.println("用户角色更新成功 - 用户ID: " + userId);
        } catch (Exception e) {
            System.out.println("更新用户角色时发生错误: " + e.getMessage());
            throw new RuntimeException("更新用户角色失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void deleteUser(Long userId) {
        System.out.println("正在删除用户 - 用户ID: " + userId);
        
        // 检查用户是否存在
        User user = userMapper.findById(userId);
        if (user == null) {
            System.out.println("用户不存在 - 用户ID: " + userId);
            throw new RuntimeException("用户不存在");
        }
        
        try {
            // 删除用户
            userMapper.delete(userId);
            System.out.println("用户删除成功 - 用户ID: " + userId);
        } catch (Exception e) {
            System.out.println("删除用户时发生错误: " + e.getMessage());
            throw new RuntimeException("删除用户失败: " + e.getMessage());
        }
    }

    @Override
    public List<User> findByRole(String roleName, Long currentUserId) {
        return userMapper.findByRole(roleName, currentUserId);
    }
} 